<template>
	<div class="report-page">
		<div class="page-title">上报事项</div>
		<van-cell-group>
			<van-field label="污染源名称" :model-value="form.pollutionSourceName" readonly required />

			<!-- 事项类别 -->
			<FormItemRadio
				label="事项类别"
				item-key="thingsCategoryCode"
				:required="true"
				v-model="form.thingsCategoryCode"
				:dic-key="'ZQT_SXLB'"
				:readonly="isView"
			/>

			<!-- 涉及内容 -->
			<FormItemCheckbox
				label="涉及内容"
				item-key="referContentCodeArr"
				:required="true"
				v-model="form.referContentCodeArr"
				:dic-key="'ZQT_WTZG_WTSJ'"
				:readonly="isView"
			/>

			<!-- 开始时间 -->
			<FormItemDateTime
				label="开始时间"
				item-key="beginTime"
				:required="true"
				v-model="form.beginTime"
				precision="minute"
				formatter="YYYY-MM-DD HH:mm"
				:readonly="isView"
				@confirm="onTimeConfirm"
			/>
			<!-- 结束时间 -->
			<FormItemDateTime
				label="结束时间"
				item-key="endTime"
				:required="true"
				v-model="form.endTime"
				precision="minute"
				formatter="YYYY-MM-DD HH:mm"
				:readonly="isView"
				@confirm="onTimeConfirm"
			/>

			<!-- 上报内容 -->
			<van-field
				label="上报内容"
				type="textarea"
				rows="3"
				autosize
				v-model="form.reportContent"
				:readonly="isView"
				:required="true"
				placeholder="请输入"
			/>

			<!-- 上报人员 -->
			<van-field label="上报人员" :model-value="form.reportUser" readonly required />
			<!-- 上报时间 -->
			<FormItemDateTime
				label="上报时间"
				item-key="createTime"
				v-model="form.createTime"
				precision="minute"
				formatter="YYYY-MM-DD HH:mm"
				:readonly="true"
			/>

			<!-- 附件上传 -->
			<FormFileUpload v-model="form.fileData" :readonly="isView" :business-id="form.id" big-type="ZQT_SBSXFJ" small-type="FJ" :required="true" />
		</van-cell-group>

		<div style="margin: 16px" v-if="!isView">
			<van-button block type="primary" @click="onSubmit" :loading="submitting">提交</van-button>
		</div>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import FormItemRadio from '@/components/form-item-radio'
import FormItemCheckbox from '@/components/form-item-checkbox/FormItemCheckbox.vue'
import FormItemDateTime from '@/components/form-item-time/FormItemDateTime.vue'
import FormFileUpload from '@/components/form-file-upload'
import Schema from 'async-validator'
import { post, get } from '@/api/request'
import { normalizeDateTime } from '../../utils/timeUtils'

export default {
	name: 'Report',
	components: { FormItemRadio, FormItemCheckbox, FormItemDateTime, FormFileUpload },
	setup() {
		const route = useRoute()
		const router = useRouter()
		const userStore = useUserStore()
		const isView = ref(route.query.isView === 'true')
		const submitting = ref(false)

		const form = reactive({
			id: generateId(),
			thingsCategoryCode: '',
			referContentCodeArr: [],
			beginTime: dayjs().format('YYYY-MM-DD HH:mm'),
			endTime: dayjs().add(1, 'hour').format('YYYY-MM-DD HH:mm'),
			reportContent: '',
			reportUser: '',
			pollutionSourceId: '',
			pollutionSourceName: '',
			createTime: dayjs().format('YYYY-MM-DD HH:mm'),
			fileData: [],
		})

		function generateId() {
			return 'ID' + Math.random().toString(16).slice(2)
		}

		const loadDetail = async (id) => {
			try {
				const res = await get(`/api/bizReportThings/get/${id}`)
				if (res.code === '0' && res.data) {
					Object.assign(form, res.data)
					// 兼容旧附件字段可能返回 fileData 已规范化
					if (!Array.isArray(form.fileData)) form.fileData = []
				} else {
					showToast(res.msg || '未查询到数据')
				}
			} catch (e) {
				console.error('加载详情失败', e)
				showToast('网络错误')
			}
		}

		const init = async () => {
			const user = await userStore.ensureLogin()
			form.reportUser = user.loginName || user.userName || ''
			form.pollutionSourceId = user?.omDepts?.id || ''
			form.pollutionSourceName = user?.omDepts?.pollutionSourceName || ''
			if (isView.value && route.query.id) {
				await loadDetail(route.query.id)
			}
		}

		const onTimeConfirm = (payload) => {
			// 结束时间不得早于开始时间
			if (payload.endTime && form.beginTime && dayjs(payload.endTime).isBefore(dayjs(form.beginTime))) {
				showToast('结束时间需晚于开始时间')
				form.endTime = dayjs(form.beginTime).add(1, 'hour').format('YYYY-MM-DD HH:mm')
			}
		}

		const descriptor = {
			thingsCategoryCode: { type: 'string', required: true, message: '请选择事项类别' },
			referContentCodeArr: { type: 'array', required: true, message: '请选择涉及内容' },
			beginTime: { type: 'string', required: true, message: '请选择开始时间' },
			endTime: {
				type: 'string',
				required: true,
				message: '请选择结束时间',
				validator: (rule, value) => !!value && dayjs(value).isAfter(dayjs(form.beginTime)),
			},
			reportContent: { type: 'string', required: true, message: '请填写上报内容' },
			fileData: { type: 'array', required: true, message: '请上传附件' },
		}

		const onSubmit = async () => {
			if (submitting.value) return
			submitting.value = true
			const params = { ...form }
			const validator = new Schema(descriptor)
			validator.validate(params, async (errors) => {
				if (errors && errors.length) {
					showToast(errors[0].message)
					submitting.value = false
					return
				}
				params.beginTime = normalizeDateTime(params.beginTime)
				params.endTime = normalizeDateTime(params.endTime)
				params.createTime = normalizeDateTime(params.createTime)
				try {
					const res = await post('/api/bizReportThings/add', params)
					if (res.code === '0') {
						showToast('操作成功')
						setTimeout(() => router.back(), 800)
					} else {
						showToast(res.msg || '提交失败')
					}
				} catch (e) {
					console.error('提交失败', e)
					showToast('网络错误，提交失败')
				} finally {
					submitting.value = false
				}
			})
		}

		onMounted(() => init())

		return {
			form,
			isView,
			submitting,
			onSubmit,
			onTimeConfirm,
		}
	},
}
</script>

<style lang="less" scoped>
.report-page {
	background: #f5f5f5;
	min-height: 100vh;
	.page-title {
		font-size: 16px;
		font-weight: 600;
		padding: 12px 16px;
		background: #fff;
		margin-bottom: 8px;
	}
}
</style>
